//
//  CYMeTool.m
//  CreditAddressBook
//
//  Created by Lee on 15/9/18.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYMeTool.h"
#import "RHPerson.h"
#import "CYCloudPerson.h"
#import "CYABTool.h"
#import "CYTool.h"
#import "CYLoginHttpTool.h"
#import "CYJsonInfo.h"
#import "MJExtension.h"
#import "RHPerson+Extension.h"

@implementation CYMeTool

+ (BOOL)addABPerson:(CYCloudPerson *)person {
     RHAddressBook *ab = [CYABTool addressBook];
     RHPerson *newPerson  = [RHPerson newPersonInSource:[ab defaultSource]];
     newPerson.lastName = person.name;
     
     RHMutableMultiStringValue *value = [[RHMutableMultiStringValue alloc] initWithType:kABMultiStringPropertyType];
     [value addValue:person.phone withLabel:RHPersonPhoneIPhoneLabel];
     
     newPerson.phoneNumbers = value;
     if ([ab addPerson:newPerson]) {
          return [ab save];
     }
     return  NO;
}

+ (void)addABPersons:(NSArray *)persons success:(void (^)(NSArray *arr))success failure:(void (^)(NSArray *arr))failure {
     if (!persons) return;
     
     NSMutableArray *successArr = [NSMutableArray array];
     NSMutableArray *failureArr = [NSMutableArray array];
     for (CYCloudPerson *person in persons) {
          if ([self addABPerson:person]) {
               [successArr addObject:person];
          } else {
               [failureArr addObject:person];
          }
     }
     
     if (success && successArr.count) {
          success(successArr);
     }
     if (failure && failureArr.count) {
          failure(failureArr);
     }
}

+ (BOOL)deleteABPerson:(CYCloudPerson *)person {
     RHAddressBook *ab = [CYABTool addressBook];
     RHPerson *rhperson = [CYABTool rhPersonWithName:person.name phones:person.phone];
     if (rhperson && [ab removePerson:rhperson]) {
          return [ab save];
     }
     return NO;
}

+ (void)deleteABPerson:(NSArray *)persons success:(void (^)(NSArray *arr))success failure:(void (^)(NSArray *arr))failure {
     if (!persons) return;
     
     NSMutableArray *successArr = [NSMutableArray array];
     NSMutableArray *failureArr = [NSMutableArray array];
     for (CYCloudPerson *person in persons) {
          if ([self deleteABPerson:person]) {
               [successArr addObject:person];
          } else {
               [failureArr addObject:person];
          }
     }
     if (success && successArr.count) {
          success(successArr);
     }
     if (failure && failureArr.count) {
          failure(failureArr);
     }
}

/**
 *  处理contacts参数
 */
+ (NSArray *)contactsArr {
     //处理数据
     NSMutableArray *contactsArr = [NSMutableArray array];
     NSArray *persons = [CYABTool reloadAllPeople];
     
     for (RHPerson *person in persons) {
          NSArray *phones = person.formatterPhones;
          if (phones.count > 0) {
               NSDictionary *contacte = nil;
               NSString *name = person.name;
               if (!name || [name.trim isEqualToString:@""]) {
                    name = phones.firstObject;
               } else {
                    //祛除姓名中的表情图片
                    name = [CYTool formatNameToZh:name];
                    if (!name || name.isEmpty) {
                         name = phones.firstObject;
                    }
               }
               
               //无头像
               if(person.thumbnail == nil) {
                    contacte = @{@"phone":phones,@"name":name,@"remark":@"",@"starred":@"0",@"hashCode":@"0"};
               } else {//有头像
                    NSData *data1 = UIImageJPEGRepresentation(person.thumbnail, 1);
                    NSString *hashCode = [NSString stringWithFormat:@"%lu", (unsigned long)data1.length];
                    contacte = @{@"phone":phones,@"name":name,@"remark":@"",@"starred":@"0",@"hashCode":hashCode, @"headerImage": person.thumbnail};
                    //                contacte = @{@"phone":person.formatterPhones,@"name":name,@"remark":@"",@"starred":@"0",@"hashCode":hashCode};
               }
               [contactsArr addObject:contacte];
          }
     }
     
     return contactsArr;
}

/**
 *  云同步
 */
+ (void)cloudSynWithSuccess:(void(^)(id json))Success failure:(HttpRequestFailure)failure uploadProgress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block {
     @try {
          //判断是否获得通讯录权限
          if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
          //判断是否登录
          CYUser *user = [CYLoginHttpTool  userData].user;
          if (!user) return;
          //获取云同步contacts参数
          NSArray *contactsArr = [CYMeTool contactsArr];
          if (contactsArr.count) {
               //去除字典中的headerImage
               NSMutableArray *newContactsArr = [NSMutableArray array];
               for (NSDictionary *dic in contactsArr) {
                    if (dic[@"headerImage"]) {
                         NSMutableDictionary *dicMu = [NSMutableDictionary dictionaryWithDictionary:dic];
                         [dicMu removeObjectForKey:@"headerImage"];
                         
                         [newContactsArr addObject:dicMu];
                    } else {
                         [newContactsArr addObject:dic];
                    }
               }
               NSTimeInterval startTime = [NSDate date].timeIntervalSinceReferenceDate;
               
               [CYHttpTool postWithURL:[CYURL getContactsByUserId] params:@{@"userId":user.userId} success:^(id json) {
                    CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
                    if (jsonInfo.isSuccess) {
                         CYLog(@"nswcont:%@",newContactsArr);
                         NSArray *getArr = jsonInfo.message;
                         NSMutableArray *resoveArr = [[NSMutableArray alloc]init];
                         NSDictionary *rsovedic = [[NSDictionary alloc]init];
                         for (NSDictionary *dic in getArr) {
                              
                              NSString *phonestr = [dic objectForKey:@"phone"];
                              NSArray *phonearr = @[phonestr];
                              NSString *name = [dic objectForKey:@"name"];
                              rsovedic = @{@"phone":phonearr,@"name":name,@"remark":@"",@"starred":@"0",@"hashCode":@"0"};
                              [resoveArr addObject:rsovedic];
                              
                         }
                         
                         CYLog(@"resoveArr = %@",resoveArr);
                         
                         
                         NSPredicate* thePredicate = [NSPredicate predicateWithFormat:@"NOT(SELF in %@)",newContactsArr];
                         NSArray *finialArr  = [resoveArr filteredArrayUsingPredicate:thePredicate];
                         NSLog(@"%@",finialArr);
                         if (finialArr.count) {
                              [CYHttpTool postWithURL:[CYURL saveContacts] params:@{@"contacts":[NSString jsonStringWithArray:finialArr],@"userId":user.userId, @"headPicFlag":@"0"} success:^(id json) {
                                   CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
                                   if (jsonInfo.isSuccess) {
                                        CYUserDefaultsAddObj(@"true", CYCloudSynKey);
                                        CYLog(@"后台云同步成功,耗时：%f", [NSDate date].timeIntervalSinceReferenceDate - startTime);
                                        
                                        if (Success) {
                                             Success(json);
                                        } else {
                                             CYUserDefaultsAddObj(@"false", CYCloudSynKey);
                                             if (failure) {
                                             }
                                        }
                                   } else {
                                        [self reportReason:@"云同步上传失败" logWarn:CYStringFormat(@"云同步上传的数据：%@", [NSString jsonStringWithArray:newContactsArr])];
                                        CYUserDefaultsAddObj(@"false", CYCloudSynKey);
                                        if (failure) {
                                        }
                                   }
                              } failure:^(NSError *error) {
                                   [self reportError:error reason:@"云同步上传失败" logError:CYStringFormat(@"云同步上传的数据：%@", [NSString jsonStringWithArray:newContactsArr])];
                                   CYUserDefaultsAddObj(@"false", CYCloudSynKey);
                                   if (failure) {
                                        failure(error);
                                   }
                              } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
                                   if (block) {
                                        block(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
                                   }
                              }];
                              
                         }
                    }
               } failure:^(NSError *error) {
                    
               }];
               
          }
     }
     @catch (NSException *exception) {
          CYLog(@"云同步错误: %@", exception);
          //  NSParameterAssert(nil);
          if (failure) {
               //            failure(CYError(@"云同步错误", CYErrorCodeError));
          }
     }
}

/**
 *  后台云同步
 */
+ (void)backgroundCloudSyn {
     //判断是否同步过
     NSString *isCloudSyn = CYUserDefaultsGetObj(CYCloudSynKey);
     if ([isCloudSyn isEqualToString:@"true"]) return;
     [self cloudSynWithSuccess:nil failure:^(NSError *error) {
          [self reportError:error reason:@"后台同步失败"];
     } uploadProgress:nil];
}
@end
